package com.koron.configure.dockingconf.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import com.koron.bean.base.Response;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.StringUtils;
import com.koron.configure.changeshift.service.ChangeShiftCFService;
import com.koron.configure.dockingconf.bean.DockingConfBean;
import com.koron.configure.dockingconf.bean.DockingConfDto;
import com.koron.configure.dockingconf.bean.DockingDetBean;
import com.koron.configure.dockingconf.bean.TipQuery;
import com.koron.configure.dockingconf.mapper.DockingConfMapper;
import com.koron.configure.dockingconf.mapper.DockingDetMapper;
import com.koron.configure.shiftTip.bean.po.ConfigureShiftTip;
import com.koron.configure.shiftTip.service.ConfigureShiftTipService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: rocky
 * @Date: 2021/11/22 16:46
 */
@Api(tags = "交接班配置 new")
@RestController
@RequestMapping("/dockingconf")
public class DockingConfController {

    @Autowired
    private ConfigureShiftTipService configureShiftTipService;

    private String getCurrDs() {
        return ThreadLocalContext.get().getCurrDs();
    }

    private EamUser getCurrUser() {
        return ThreadLocalContext.get();
    }

    @Autowired
    private ChangeShiftCFService service;

    @ApiOperation(value = "交接班配置-左-列表")
    @GetMapping("queryList")
    public Response<List> queryList(DockingConfDto dto) {

        List<DockingConfBean> list = ADOConnection.runTask(getCurrDs(), factory -> {
            return factory.getMapper(DockingConfMapper.class).queryByAll(dto);
        }, List.class);
        return Response.ok(list);
    }

    @ApiOperation(value = "交接班配置-左-新建")
    @GetMapping("addDockingconf")
    public Response<String> addDockingconf(DockingConfDto dto) {
        String id = ADOConnection.runTask(getCurrDs(), factory -> {
            DockingConfMapper mapper = factory.getMapper(DockingConfMapper.class);
            // 不能重复
            List<DockingConfBean> dock = mapper.queryByAll(dto);//获取左边
            Assert.isTrue(CollectionUtils.isEmpty(dock), "不能重复");
            DockingConfBean bean = Convert.convert(DockingConfBean.class, dto);
            bean.setId(IdUtil.simpleUUID());
            mapper.insertSelective(bean);
            return bean.getId();
        }, String.class);
        return Response.ok(id);
    }

    @ApiOperation(value = "交接班配置-左-更新")
    @GetMapping("updateDockingconf")
    public Response<String> updateDockingconf(DockingConfDto dto) {
        DockingConfBean bean = Convert.convert(DockingConfBean.class, dto);
        ADOConnection.runTask(getCurrDs(), factory -> {
            DockingConfMapper mapper = factory.getMapper(DockingConfMapper.class);
            // 不能重复
            List<DockingConfBean> dock = mapper.queryByAll(dto);//获取左边
            Assert.isTrue(CollectionUtils.isEmpty(dock), "不能重复");
            mapper.updateByPrimaryKeySelective(bean);
            return dto.getId();
        }, String.class);
        return Response.ok(dto.getId());
    }


    @ApiOperation(value = "交接班配置-左-删除")
    @DeleteMapping("deleteById")
    public Response<String> deleteById(@RequestParam(value = "id") String id) {
        ADOConnection.runTask(getCurrDs(), factory -> {
            configureShiftTipService.removeByDockingId(factory, id);
            factory.getMapper(DockingConfMapper.class).deleteByPrimaryKey(id);
            return true;
        }, Boolean.class);
        return Response.ok("成功");
    }


    @Deprecated
    @ApiOperation(value = "交接班配置-右-列表")
    @GetMapping("queryDetList")
    public Response<List> queryDetList(@RequestParam(value = "id", required = true) String id) {

        List<DockingDetBean> list = ADOConnection.runTask(getCurrDs(), factory -> {
            DockingDetMapper mapper = factory.getMapper(DockingDetMapper.class);
            List<DockingDetBean> docklist = mapper.queryByDockingId(id);
            List<DockingDetBean> resultlist = docklist.stream().filter(d -> StringUtils.isEmpty(d.getParentId())).sorted(Comparator.comparing(DockingDetBean::getSort)).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(resultlist)) {
                resultlist.stream().forEach(d -> {
                    List<DockingDetBean> collect = Optional.ofNullable(docklist.stream().filter(c -> d.getId().equals(c.getParentId())).sorted(Comparator.comparing(DockingDetBean::getSort)).collect(Collectors.toList())).orElse(new ArrayList<>());
                    d.setChildren(collect);
                });
            }
            return resultlist;
        }, List.class);
        return Response.ok(list);
    }

    @Deprecated
    @ApiOperation(value = "交接班配置-jzp远程调-列表")
    @GetMapping("jzpqueryDetList")
    public Response<List> jzpqueryDetList(DockingConfDto dto) {
        List<DockingDetBean> list = ADOConnection.runTask(getCurrDs(), factory -> {
            List<DockingConfBean> dock = factory.getMapper(DockingConfMapper.class).queryByAll(dto);//获取左边
            List<String> parentIds = dock.stream().map(DockingConfBean::getId).collect(Collectors.toList());
            if(StringUtils.isEmpty(parentIds)){
                return new ArrayList<>();
            }
            List<DockingDetBean> temlist = factory.getMapper(DockingDetMapper.class).queryInDockingId(parentIds);//获取对应右边
            Map<String, DockingDetBean> firstmap = temlist.stream().filter(t -> StringUtils.isEmpty(t.getParentId())).collect(Collectors.toMap(DockingDetBean::getId, e -> e));//获取一级项
            List<DockingDetBean> secondlist = temlist.stream()
                    .filter(t -> StringUtils.isNotEmpty(t.getSecondLevel()) && dto.getDisplayFlag().equals(t.getDisplayFlag()))
                    .collect(Collectors.toList());//获取一级项
            secondlist.forEach(s->{
                s.setFirstLevel(firstmap.get(s.getParentId()).getFirstLevel());
                s.setSort(firstmap.get(s.getParentId()).getSort());
            });
            secondlist.sort(Comparator.comparing(DockingDetBean::getSort));
            return secondlist;
        }, List.class);
        return Response.ok(list);
    }


    @ApiOperation(value = "交接班配置-jzp远程调-列表")
    @GetMapping("tipList")
    public Response<List<ConfigureShiftTip>> tipList(TipQuery query) {
        List<ConfigureShiftTip> list = ADOConnection.runTask(getCurrDs(), factory -> {
            DockingConfBean dock = factory.getMapper(DockingConfMapper.class).queryByTip(query);//获取左边
            if(dock == null){
                return new ArrayList<>();
            }
            return configureShiftTipService.listByDockingId(factory, dock.getId());
        }, List.class);
        return Response.ok(list);
    }

    @Deprecated
    @ApiOperation(value = "交接班配置-右-新建、保存")
    @PostMapping("addDockingDet")
    public Response<String> addDockingDet(@RequestBody DockingDetBean bean) {

        Assert.isFalse(StringUtils.isNull(bean.getDockingId()), "值班地点id不能为空");
        Assert.isFalse(StringUtils.isNull(bean.getSort()), "排序号不能空");

        ADOConnection.runTask(getCurrDs(), factory -> {
            DockingDetMapper mapper = factory.getMapper(DockingDetMapper.class);

            String oneid = bean.getId();
            if (StringUtils.isNotEmpty(oneid)) {
                mapper.deleteByParentId(oneid);//先删除该一级项，所有子集
                mapper.updateByPrimaryKeySelective(bean);
            } else {
                bean.setId(IdUtil.simpleUUID());
                factory.getMapper(DockingDetMapper.class).insertSelective(bean);
            }

            bean.getChildren().stream().forEach(b -> {
                b.setId(IdUtil.simpleUUID());
                b.setParentId(bean.getId());
                b.setDockingId(bean.getDockingId());
            });

            factory.getMapper(DockingDetMapper.class).batchInsert(bean.getChildren());
            return bean.getDockingId();
        }, String.class);
        return Response.ok(bean.getDockingId());
    }

    @Deprecated
    @ApiOperation(value = "交接班配置-右-编辑按钮")
    @GetMapping("detailsDockingDet")
    public Response<DockingDetBean> detailsDockingDet(String id) {

        DockingDetBean result = ADOConnection.runTask(getCurrDs(), factory -> {
            DockingDetMapper mapper = factory.getMapper(DockingDetMapper.class);
            DockingDetBean dockingDetBean = mapper.selectByPrimaryKey(id);
            List<DockingDetBean> det = mapper.queryAllByParentId(id);
            dockingDetBean.setChildren(det);

            return dockingDetBean;
        }, DockingDetBean.class);
        return Response.ok(result);
    }

    @Deprecated
    @ApiOperation(value = "交接班配置-右-两个删除")
    @DeleteMapping("deleteDetById")
    public Response<String> deleteDetById(@RequestParam(value = "id") String id) {
        ADOConnection.runTask(getCurrDs(), factory -> {
            DockingDetMapper mapper = factory.getMapper(DockingDetMapper.class);
            mapper.deleteByParentId(id);
            mapper.deleteByPrimaryKey(id);
            return true;
        }, Boolean.class);
        return Response.ok("成功");
    }

}
